package top.cdmrx.demo.edu.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import top.cdmrx.common.R;
import top.cdmrx.demo.edu.entity.Video;
import top.cdmrx.demo.edu.service.VideoService;
import top.cdmrx.demo.edu.client.VodClient;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2021-09-18
 */
@RestController
@RequestMapping("/edu/video")
@CrossOrigin
public class VideoController {
    @Autowired
    private VideoService videoService;

    @Autowired
    private VodClient vodClient;

    //添加小节
    @PostMapping("addVideo")
    public R addVideo(@RequestBody Video video){
        videoService.save(video);
        return R.success();
    }

    //删除小节
    @DeleteMapping("{id}")
    public R deleteVideo(@PathVariable String id){
        //根据小节id获取视频对象
        Video video = videoService.getById(id);
        //获取视频id
        String videoSourceId = video.getVideoSourceId();
        //判断若有视频就删除
        if (!StringUtils.isEmpty(videoSourceId)){

            R r = vodClient.removeAlyVideo(videoSourceId);
            if (r.getCode() == 20001){
                throw new RuntimeException("删除视频失败，熔断器执行。");
            }
        }

        //视频删除后再删除小节
        videoService.removeById(id);
        return R.success();
    }

    //修改小节
    //根据id查询出指定的小节
    @GetMapping("{id}")
    public R getVideoById(@PathVariable String id){
        Video byId = videoService.getById(id);
        return R.success().data("getVideo",byId);
    }

    //真正的修改方法
    @PutMapping("updateVideo")
    public R updateVideo(@RequestBody Video video){
        boolean b = videoService.updateById(video);
        if (b){

            return R.success();
        }else {
            return  R.fail();
        }
    }
}

